from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


def generate_openid_signature(openid):
    """加密openid函数"""
    # 创建实例对象 参数：(唯一加密字符串使用django自带SECRET_KEY,过期时间这里与code一致600）
    serializer = Serializer(settings.SECRET_KEY, 600)
    data = {'openid':openid}
    openid_sign = serializer.dumps(data)  # 加密得到的是byte类型
    return openid_sign.decode()


def check_openid_signature(openid_sign):
    """解密openid函数"""
    # 创建实例对象,参数必须与加密时参数一致
    serializer = Serializer(settings.SECRET_KEY, 600)
    # 解密时有可能加密内容已经过期
    try:
        # 加密时是字典类型解密返回原样
        data = serializer.loads(openid_sign)
        return data.get('openid')
    except BadData:
        return None
